package com.zhugang.week13.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program algorithms
 * @description: maxDepth
 * @author: chanzhugang
 * @create: 2022/12/17 01:27
 */
public class MaxDepth2 {

    /**
     * 104、二叉树的最大深度
     * https://leetcode.cn/problems/maximum-depth-of-binary-tree/
     *
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        /**
         * 深度优先搜索
         * max(左子树最大深度，右子树最大深度) + 1
         */
        return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }

    public int maxDepth2(TreeNode root) {
        /**
         * 广度优先搜索: 取出每层的节点
         */
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int depth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                // 遍历每一层所有节点
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
            depth++;
        }
        return depth;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}